<!-- src/views/Permission/component/user.vue -->
<template>
  <div class="user-management">
    <h2>用户管理</h2>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline>
      <el-form-item label="用户名">
        <el-input
          v-model="searchForm.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-button type="primary" @click="handleAddUser" icon="Plus">新增用户</el-button>

    <!-- 表格 -->
    <el-table
      :data="sysUserStore.users"
      style="width: 100%; margin-top: 20px;"
      border
      v-loading="sysUserStore.loading"
      stripe
    >
      <el-table-column prop="id" label="用户ID" width="180" align="center"></el-table-column>
      <el-table-column prop="userName" label="用户名" width="120" align="center"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="150" align="center"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="180" align="center">
        <template #default="{ row }">
          <div v-if="row.roles && row.roles.length > 0">
            <el-tag v-for="role in row.roles" :key="role.id" size="small">
              {{ role.roleName }}
            </el-tag>
          </div>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)" type="primary">编辑</el-button>
          <el-button
            size="small"
            @click="handleToggleStatus(row)"
            :type="row.status === 1 ? 'danger' : 'success'"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          <el-button size="small" @click="handleAssignRole(row)">分配角色</el-button>
          <el-button size="small" @click="handleUnassignRole(row)">解除绑定</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="sysUserStore.total"
      style="margin-top: 20px; text-align: right;"
    ></el-pagination>

    <!-- 弹窗表单 -->
    <el-dialog
      :title="operationType === 'add' ? '新增用户' : '编辑用户'"
      v-model="dialogFormVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" :disabled="operationType === 'edit'" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            :placeholder="operationType === 'add' ? '请输入密码' : '不修改请留空'"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog
      title="分配角色"
      v-model="assignRoleDialogVisible"
      width="500px"
    >
      <el-form label-width="80px">
        <el-form-item label="用户">
          {{ selectedUserId }}
        </el-form-item>
        <el-form-item label="选择角色">
          <el-select
            v-model="selectedRoleId"
            placeholder="请选择角色"
            clearable
            :loading="loadingRoles"
          >
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelAssignRole">取消</el-button>
        <el-button type="primary" @click="confirmAssignRole">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useSysUserStore } from '@/stores/sysUser'
import { ElMessage, ElMessageBox } from 'element-plus'

const sysUserStore = useSysUserStore()

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索相关
const searchForm = ref({
  userName: ''
})

// 表单弹窗控制
const dialogFormVisible = ref(false)
const form = ref({
  userName: '',
  phone: '',
  email: '',
  password: '',
  status: 1
})

// 表单验证规则
const formRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 操作类型：add / edit
const operationType = ref('add')
const editingUserId = ref(null)

// 角色分配弹窗
const assignRoleDialogVisible = ref(false)
const selectedUserId = ref(null)
const selectedRoleId = ref(null)
const roles = ref([]) // 所有角色列表
const loadingRoles = ref(false) // 加载状态

// 加载数据
onMounted(() => {
  sysUserStore.fetchUsers(currentPage.value, pageSize.value)
})

// 获取角色列表
const loadRoles = async () => {
  loadingRoles.value = true
  try {
    const roleList = await sysUserStore.getRoles() // 调用 store 中的方法
    roles.value = roleList.map(role => ({
      id: role.id,
      roleName: role.roleName
    }))
  } catch (error) {
    ElMessage.error('加载角色失败：' + error.message)
  } finally {
    loadingRoles.value = false
  }
}

// 新增用户
const handleAddUser = () => {
  operationType.value = 'add'
  form.value = {
    userName: '',
    phone: '',
    email: '',
    password: '',
    status: 1
  }
  editingUserId.value = null
  dialogFormVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  operationType.value = 'edit'
  editingUserId.value = row.id
  form.value = {
    userName: row.userName,
    phone: row.phone,
    email: row.email,
    password: '', // 编辑时密码字段为空，如果需要修改密码则单独填写
    status: row.status
  }
  dialogFormVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除用户 ${row.userName} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result = await sysUserStore.deleteUser(row.id)
    if (result.success) {
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}用户 ${row.userName} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await sysUserStore.toggleUserStatus(row.id)
    if (result.success) {
      ElMessage.success('状态切换成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '状态切换失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    let result
    if (operationType.value === 'add') {
      result = await sysUserStore.addUser(form.value)
    } else {
      // 编辑时如果密码为空，则不传递密码字段
      const userData = { ...form.value }
      if (!userData.password) {
        delete userData.password
      }
      result = await sysUserStore.updateUser(editingUserId.value, userData)
    }

    if (result.success) {
      ElMessage.success('操作成功')
      dialogFormVisible.value = false
    }
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  if (searchForm.value.userName.trim() !== '') {
    handleSearch(1, val)
  } else {
    sysUserStore.fetchUsers(currentPage.value, val)
  }
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  if (searchForm.value.userName.trim() !== '') {
    handleSearch(val, pageSize.value)
  } else {
    sysUserStore.fetchUsers(val, pageSize.value)
  }
}

// 搜索功能
const handleSearch = async (page = 1, size = pageSize.value) => {
  try {
    await sysUserStore.searchUsersByUsername(searchForm.value.userName.trim(), page, size)
    currentPage.value = page
  } catch (error) {
    ElMessage.error('搜索失败: ' + error.message)
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.userName = ''
  currentPage.value = 1
  sysUserStore.fetchUsers(currentPage.value, pageSize.value)
}

// 分配角色
const handleAssignRole = async (row) => {
  selectedUserId.value = row.id
  await loadRoles() // 加载角色列表
  assignRoleDialogVisible.value = true
}

// 确认分配角色
const confirmAssignRole = async () => {
  if (!selectedRoleId.value) {
    ElMessage.warning('请选择一个角色')
    return
  }

  try {
    const result = await sysUserStore.assignRole(selectedUserId.value, selectedRoleId.value)
    if (result.success) {
      ElMessage.success('角色分配成功')
      assignRoleDialogVisible.value = false
      // 重新加载当前数据
      if (searchForm.value.userName.trim() !== '') {
        handleSearch(currentPage.value, pageSize.value)
      } else {
        await sysUserStore.fetchUsers(currentPage.value, pageSize.value)
      }
    }
  } catch (error) {
    ElMessage.error(error.message || '分配失败')
  }
}

// 取消分配
const cancelAssignRole = () => {
  assignRoleDialogVisible.value = false
  selectedRoleId.value = null
}

// 解除角色绑定
const handleUnassignRole = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要解除用户 ${row.userName} 的角色绑定吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const roleId = row.roles?.[0]?.id
    if (!roleId) {
      ElMessage.warning('该用户未绑定任何角色')
      return
    }

    const res = await sysUserStore.unassignRole(row.id, roleId)
    if (res.success) {
      ElMessage.success('角色解除成功')
      // 重新加载当前数据
      if (searchForm.value.userName.trim() !== '') {
        handleSearch(currentPage.value, pageSize.value)
      } else {
        await sysUserStore.fetchUsers(currentPage.value, pageSize.value)
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '解除失败')
    }
  }
}
</script>

<style scoped lang="scss">
.user-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;

  .el-table {
    margin-top: 20px;
  }

  .el-pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style>